#coding:utf-8
import os
from pickle import FALSE
import requests
import json
from bs4 import BeautifulSoup

#https://n8k6e2y6.ssl.hwcdn.net/repos/hnfvc0o3jnfvc873njb03enrf56.html#relicRewards
#PC 平台官方掉落表



def get_ducats():
    r = requests.get('https://warframe.market/tools/ducats')
    #print(r.status_code)
    #print(r.text)
    #<script type="application/json" id="application-state"> 本地数据
    soup = BeautifulSoup(r.text,'lxml')
    #json数据
    ducats=json.loads(soup('script')[2].string)
    temp=json.dumps(ducats)
    f=open(r"ducats.json","w")
    temp="var ducats =" +temp
    f.write(temp)
    f.close()
    return ducats

try:
    ducats = get_ducats()
    print("联网数据")
except:
    f=open(r"ducats.json","r")
    temp=f.read()
    f.close()
    for i in range(len(temp)):
        if (temp[i]=="{"):
            temp=temp[i:]
            break
    ducats=json.loads(temp)
    print("本地数据")

DucatsItemDic={}
for i in ducats["items"]:
    DucatsItemDic[i["id"]]=i["item_name"]

DucatsItemData={}
for i in ducats["payload"]["previous_day"]:
    DucatsItemData[DucatsItemDic[i["item"]]]={
        "ducats":i["ducats"],
        "wa_price":i["wa_price"],
        "ducats_per_platinum_wa":i["ducats_per_platinum_wa"]
        }
#DucatsItemData[item]={"ducats":0,"wa_price":0,"ducats_per_platinum_wa":0}
print("获取杜卡德金币价值数据",DucatsItemData)



f=open(r"ItemPrice.txt","w")
temp="Item,price\n"
for i in DucatsItemData:
    temp+=i+","+str(DucatsItemData[i]["wa_price"])+"\n"
f.write(temp)
f.close()
print("杜卡德金币价值数据写入txt")




#核桃数据
def get_void_data():
    r = requests.get('https://warframe.fandom.com/wiki/Module:Void/data?oldid=2245660')
    print(r.text)
    soup = BeautifulSoup(r.text,'lxml')
    void_data=soup.find_all('pre')[3].text
    print(void_data)
    #核桃数据数据格式
    '''
    {
        "Drops":[
            {"Item":"","Part":"","Rarity":""},
            {"Item":"","Part":"","Rarity":""},
            {"Item":"","Part":"","Rarity":""},
            {"Item":"","Part":"","Rarity":""},
            {"Item":"","Part":"","Rarity":""},
            {"Item":"","Part":"","Rarity":""}]
        "Vaulted":False
    }
    '''
    RelicData={}
    _void=""
    _type=""
    _drop=""
    _count_number=0
    _flag=False
    deep_count=-1
    line=""
    for i in void_data:
        if(deep_count==0):
            break
        if(i=="\n"):
            #print(deep_count)
            #line.replace("  "," ")
            if("--" in line or "local" in line):
                print("注释行")
                #print(line)
                line=""
                continue
            if("RelicData" in line):
                deep_count = 1
                #print(line)
                print("找到入口")
                line=""
                continue
            if(deep_count>0):
                if("Vaulted" in line or "IsBaro" in line):
                    #判断是否入库
                    RelicData[_void]["Vaulted"]=True
                #添加新类型核桃
                elif("["in line):
                    if(not _void=="" ):
                        print(_void)
                        print(RelicData[_void])
                    #print("添加新类型核桃")
                    _void=""
                    _count_number=0
                    for j in line:
                        if(j=='"'):
                            _flag=not _flag
                        if(j.isalnum() or (_flag and j==" ")):
                            _void+=j
                    #核桃名称汉化
                    #古纪,Lith  前纪,Meso   中纪,Neo    后纪,Axi  
                    _void=_void.replace("Lith","古纪")
                    _void=_void.replace("Meso","前纪")
                    _void=_void.replace("Neo","中纪")
                    _void=_void.replace("Axi","后纪")
                    deep_count=deep_count+1
                    RelicData[_void]={"Drops":[{"Item":"","Part":"","Rarity":""},{"Item":"","Part":"","Rarity":""},{"Item":"","Part":"","Rarity":""},{"Item":"","Part":"","Rarity":""},{"Item":"","Part":"","Rarity":""},{"Item":"","Part":"","Rarity":""}]}
                    line=""
                    _type=""
                    _drop=""
                    RelicData[_void]["Vaulted"]=False
                    continue
                elif("Item" in line):
                    for j in line:
                        if(j =="{"):deep_count=deep_count+1
                        if(j =="}"):deep_count=deep_count-1
                        if(j=="," or j=="}" and not _drop==""):
                            RelicData[_void]["Drops"][_count_number][_type]=_drop
                            #print(_type)
                            #print(RelicData[_void]["Drops"][_count_number])
                            _type=""
                            _drop=""
                        if(j=='"'):
                            _flag=not _flag
                            continue
                        if(j.isalnum() or (_flag and j==" ") or j=="&"):
                            if(_flag):
                                _drop+=j
                                continue
                            _type+=j
                            continue
                    line=""
                    _count_number+=1
                    continue
                for j in line:
                    #处理单行内容
                    if(j =="{"):deep_count=deep_count+1
                    if(j =="}"):
                        deep_count=deep_count-1
            line=""
            continue    
        line+=i
    #print(RelicData["Neo T5"]["Drops"][1]["Item"])
    #print(RelicData["Axi A3"])
    temp=json.dumps(RelicData)
    f=open(r"RelicData.json","w")
    temp="var RelicData =" +temp
    f.write(temp)
    f.close()
    return RelicData
    #   elicData_zh     最后的核桃数据
    #古纪,Lith  前纪,Meso   中纪,Neo    后纪,Axi            
    #print(RelicData["Axi A10"])
    #print(RelicData["前纪 P6"])
    #print(RelicData["Axi A3"]["Vaulted"])
    #print(RelicData_zh)

RelicData={}
try:
    RelicData = get_void_data()
    print("核桃明细，联网数据")
    #读取本地文件
except:
    f=open(r"RelicData.json","r")
    temp=f.read()
    f.close()
    for i in range(len(temp)):
        if (temp[i]=="{"):
            temp=temp[i:]
            break
    RelicData=json.loads(temp)
    print("核桃明细，本地数据")
print("核桃明细数据",RelicData)


def item_ptice(item_name):
    price=0
    try:
        price=DucatsItemData[item_name]["wa_price"]
    except KeyError:
        if("Blueprint" in item_name and "Kavasa" not in item_name):
            item_name=item_name[:-10]
        if(item_name=="Kavasa Prime Collar Blueprint"):
            item_name="Kavasa Prime Kubrow Collar Blueprint"
        if(item_name=="Kavasa Prime Kubrow Collar Buckle"):
            item_name="Kavasa Prime Buckle"
        if(item_name=="Kavasa Prime Kubrow Collar Band"):
            item_name="Kavasa Prime Band"
        price=DucatsItemData[item_name]["wa_price"]
    return price


#计算核桃价值
RelicPrice={}
#遗物	完	光	差	类
#常见,Common     罕见,Uncommon    稀有,Rare
#完整	76% (25.33%)	22% (11%)	2%
#光辉	50% (16.67%)	40% (20%)	10%
#四光   0.0625    0.5936   0.3439   
def cont_price(RelicName):
    RelicPrice[RelicName]={"系数":0,"类别":""}
    print(RelicName)
    for i in range(6):
        if(RelicData[RelicName]["Drops"][i]["Item"]=="Forma"):
            print("Forma")
            continue
        _item=RelicData[RelicName]["Drops"][i]["Item"]+" "+RelicData[RelicName]["Drops"][i]["Part"]
        #DucatsItemData[item]={"ducats":0,"wa_price":0,"ducats_per_platinum_wa":0}
        if(RelicData[RelicName]["Drops"][i]["Rarity"]=="Common"):
            RelicPrice[RelicName]["系数"]+=(item_ptice(_item)*0.0625/3)
        elif(RelicData[RelicName]["Drops"][i]["Rarity"]=="Uncommon"):
            RelicPrice[RelicName]["系数"]+=(item_ptice(_item)*0.5936)
        else:#稀有
            RelicPrice[RelicName]["系数"]+=(item_ptice(_item)*0.3439)
        print(_item,item_ptice(_item),RelicData[RelicName]["Drops"][i]["Rarity"])
    RelicPrice[RelicName]["系数"]=round(RelicPrice[RelicName]["系数"],2)
    if(RelicName[:2]=="古纪"):RelicPrice[RelicName]["类别"]="T1"
    elif(RelicName[:2]=="前纪"):RelicPrice[RelicName]["类别"]="T2"
    elif(RelicName[:2]=="中纪"):RelicPrice[RelicName]["类别"]="T3"
    else:RelicPrice[RelicName]["类别"]="T4"
    print(RelicPrice[RelicName])
    pass

for RelicName in RelicData:
    if ("Requiem" in RelicName):
        continue
    cont_price(RelicName)





#获取中英对照表
def get_WF_Dict():
    r = requests.get('https://raw.githubusercontent.com/Richasy/WFA_Lexicon/WFA5/WF_Dict.json')
    r_json=json.loads(r.text)
    _dict={}
    for i in r_json:
        _dict[i["en"]]=i["zh"]
        print(i["en"]+":"+i["zh"])
    f_1=open(r"WF_Dict.json","w")
    temp=json.dumps(_dict)
    temp="var WF_Dict =" +temp
    f_1.write(temp)
    f_1.close()
    return _dict

try:
    last_time=os.path.getmtime('WF_Dict.json')
    _dict = get_WF_Dict()
    print("联网数据")
except:
    f=open(r"WF_Dict.json","r")
    temp=f.read()
    f.close()
    for i in range(len(temp)):
        if (temp[i]=="{"):
            temp=temp[i:]
            break
    _dict=json.loads(temp)
    print("本地数据")
    #读取本地文件

#根据名字及词典翻译
def en_to_zh(_key,flag=False):
    zh_name=""
    if(_key=="Gauntlet"):return "拳套"
    if (" "in _key):
        max_char_num=len(_key)
        try:
            zh_name=_dict[_key]
        except KeyError:
            #print(_key+"0000"+_key[-5:])
            if(_key[-5:]=="Prime"):
                #print("1111111111111111111111")
                try:
                    zh_name=en_to_zh(_key[:-6])+" Prime"
                    #print("#####"+zh_name+"#####")
                    return zh_name
                except KeyError:
                    return _key
            if(flag):
                raise KeyError
            for i in range(max_char_num):
                if(_key[max_char_num-i-1]==" "):
                    try:
                        #print("####"+_key[:max_char_num-i-1]+"####"+_key[max_char_num-i:]+"####")
                        zh_name=en_to_zh(_key[:max_char_num-i-1],True)+en_to_zh(_key[max_char_num-i:])
                        return zh_name
                    except KeyError:
                        continue
            zh_name=_key             
    else:
        try:
           zh_name=_dict[_key]
        except KeyError:
           zh_name=_key
    return zh_name


en_to_zh("Vauban Prime Neuroptics Blueprint")
en_to_zh("Paris Prime Upper Limb")
en_to_zh("Kavasa Prime Kubrow Collar Blueprint")
#Aksomati Prime Blueprint



#生成部件词典
PartName_zh={}
_item=""
_Rarity=""
for item_name in RelicData:
    for i in range(6):
        if(RelicData[item_name]["Drops"][i]["Item"]=="Forma"):
                continue
        _item=RelicData[item_name]["Drops"][i]["Item"]+" "+RelicData[item_name]["Drops"][i]["Part"]
        PartName_zh[_item]=en_to_zh(_item)

#输出验证
for item_name in PartName_zh:
    print(item_name,PartName_zh[item_name])

f_1=open(r"PartName_zh.json","w")
temp=json.dumps(PartName_zh)
temp="var PartName_zh =" +temp
f_1.write(temp)
f_1.close()

#添加核桃金部件是啥
for item_name in RelicPrice:
    _item=""
    #print (item_name)
    #print (RelicPrice[item_name])
    #print (RelicData[item_name]["Drops"][5]["Item"])
    #print (RelicData[RelicName]["Drops"][5]["Rarity"])
    _item=RelicData[item_name]["Drops"][5]["Item"]+" "+RelicData[item_name]["Drops"][5]["Part"]
    #print (_item)
    RelicPrice[item_name]["金"]=en_to_zh(_item)


f=open(r"RelicPrice_en.txt","w")
f.write("遗物,系数,类,金\n")
for RelicName in RelicPrice:
    f.write(RelicName+","+str(RelicPrice[RelicName]["系数"])+","+RelicPrice[RelicName]["类别"]+","+RelicPrice[RelicName]["金"]+"\n")

f.close()



temp=json.dumps(RelicPrice)
f=open(r"RelicPrice.json","w")
temp="var RelicPrice =" +temp
f.write(temp)
f.close()



#出库核桃部件收集统计
#核桃数据数据格式
'''
{
    "Drops":[
        {"Item":"","Part":"","Rarity":""},
        {"Item":"","Part":"","Rarity":""},
        {"Item":"","Part":"","Rarity":""},
        {"Item":"","Part":"","Rarity":""},
        {"Item":"","Part":"","Rarity":""},
        {"Item":"","Part":"","Rarity":""}]
    "Vaulted":False
}
'''
IntroducedPart={}
_item=""
_Rarity=""
for item_name in RelicData:
    if("Requiem" in item_name):
        continue
    if(not RelicData[item_name]["Vaulted"]):
        for i in range(6):
            if(RelicData[item_name]["Drops"][i]["Item"]=="Forma"):
                continue
            _item=RelicData[item_name]["Drops"][i]["Item"]+" "+RelicData[item_name]["Drops"][i]["Part"]
            if(RelicData[item_name]["Drops"][i]["Rarity"]=="Common"):
                _Rarity="铜"
            elif(RelicData[item_name]["Drops"][i]["Rarity"]=="Uncommon"):
                _Rarity="银"
            else:
                _Rarity="金"
            try:
                IntroducedPart[_item].append({"Relic":item_name,"Rarity":_Rarity})
            except KeyError:
                IntroducedPart[_item]=[{"Relic":item_name,"Rarity":_Rarity}]

temp=json.dumps(IntroducedPart)
f=open(r"IntroducedPart.json","w")
temp="var IntroducedPart =" +temp
f.write(temp)
f.close()


Introduced_Item=[]

def Show_Introduced():
    for item_name in RelicData:
        if("Requiem" in item_name):
            continue
        if(not RelicData[item_name]["Vaulted"]):
            for i in range(6):
                _item=RelicData[item_name]["Drops"][i]["Item"]
                if (_item in Introduced_Item):
                    continue
                else:
                    Introduced_Item.append(_item)
    pass
    print(Introduced_Item)

Show_Introduced()



exit()